<script setup lang="ts">
import type { DataTableColumns } from 'naive-ui';
import { NButton } from 'naive-ui';
import {h, ref, watch} from 'vue';
import ExceptionDetail from "@/views/duplicate-check/check-result/modules/exception-detail.vue";
import {useBoolean} from "~/packages/hooks";

interface Props {
  fileNumber?: number;
  compareName?: string;
  compareData?: any;
}

const props = withDefaults(defineProps<Props>(), {
  fileNumber: 0,
  compareName: '',
  compareData: {}
});

const { bool: showDetailModal, setTrue: openDetailModal } = useBoolean();

type RowData = {
  id: number;
  title: string;
  createTime: string;
  rankId: number;
  parentId: number;
  logId: number;
  type: number;
};

let columns: DataTableColumns<RowData> = [];

const defaultColumns: DataTableColumns<RowData> = [
  {
    title: '',
    key: 'title',
    align: 'center'
  }
];

let contentsColumns: DataTableColumns<RowData> = [];

let tableData: RowData[] = [];

/**
 * 1、总相似量 total
 * 2、正文相似量 zhengwen
 * 3、目录相似量 mulu
 * 4、字体字号相似量 zitizihao
 * 5、图片相似量 tupian
 * 6、批注识别 pizhu
 * 7、投标人名称查询 mingcheng
 * 8、投标人地址查询 dizhi
 * 9、法人查重 faren
 * 10、报价规律性 baojia
 * 11、投标保证金付款单位 baozhengjin
 * 12、投标文件编辑时间 shijian
 * 13、投标文件编辑作者 zuozhe
 */

const titleMap: any[] = [
  {
    title: '总相似量',
    key: 'total',
    index: 0
  },
  {
    title: '正文相似量',
    key: 'zhengwen',
    index: 1
  },
  {
    title: '目录相似量',
    key: 'mulu',
    index: 2
  },
  {
    title: '字体字号相似量',
    key: 'zitizihao',
    index: 3
  },
  {
    title: '图片相似量',
    key: 'tupian',
    index: 4
  },
  {
    title: '批注识别',
    key: 'pizhu',
    index: 5
  },
  {
    title: '投标人名称查询',
    key: 'mingcheng',
    index: 6
  },
  {
    title: '投标人地址查询',
    key: 'dizhi',
    index: 7
  },
  {
    title: '法人查重',
    key: 'faren',
    index: 8
  },
  {
    title: '报价规律性',
    key: 'baojia',
    index: 9
  },
  {
    title: '投标保证金付款单位',
    key: 'baozhengjin',
    index: 10
  },
  {
    title: '投标文件编辑时间',
    key: 'shijian',
    index: 11
  },
  {
    title: '投标文件编辑作者',
    key: 'zuozhe',
    index: 12
  }
];

watch(
  () => props.compareData,
  value => {
    if (value) {
      dataReorganization();
    }
  },
  { immediate: true, deep: true }
);

const selectedIndex = ref<number>(0);
const selectedData = ref<any>();
const checkContent = ref<any[]>();

// 数据重组处理
function dataReorganization() {
  contentsColumns = [];
  tableData = [];
  for (let i: number = 0; i < props.compareData.list[props.fileNumber].map.length; i++) {
    const mapData: any = props.compareData.list[props.fileNumber].map[i];
    contentsColumns.push({
      title: `投标单位${mapData.compare}-${mapData.compareName}`,
      key: `title${i}`,
      align: 'center',
      align: 'center',
      children: [
        {
          title: '异常数量',
          key: `anomaliesNum_${i}`,
          align: 'center',
          render(item: RowData, index: number) {
            let itemStyle: string = 'height: 32px; font-family: HarmonyOS Sans SC; font-weight: 400; font-size: 16px;';
            if (item.title === titleMap[0].title) {
              itemStyle += 'color: #666666;';
            } else {
              itemStyle += 'color: #806CFE;';
            }
            return h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                size: 'small',
                style: `${itemStyle}`,
                onClick: () => {
                  // console.log("item: ", i, index, item);
                  // console.log('compareData: ', props.compareData);
                  if (item.title === titleMap[0].title) return;

                  selectedIndex.value = i;
                  checkContent.value = props.compareData.checkContent;
                  selectedData.value = item;
                  openDetailModal();
                }
              },
              { default: () => item[`anomaliesNum_${i}`] } // 按钮显示名称
            );
          }
        },
        {
          title: '相似比例',
          key: `similarityRatio_${i}`,
          align: 'center',
          render(item: RowData, index: number) {
            let itemStyle: string = 'height: 32px; font-family: HarmonyOS Sans SC; font-weight: 400; font-size: 16px;';
            if (item.title === titleMap[0].title) {
              itemStyle += 'color: #666666;';
            } else {
              itemStyle += 'color: #806CFE;';
            }
            return h(
              NButton,
              {
                type: 'primary',
                quaternary: true,
                size: 'small',
                style: `${itemStyle}`,
                onClick: () => {
                  if (item.title === titleMap[0].title) return;

                  selectedIndex.value = i;
                  checkContent.value = props.compareData.checkContent;
                  selectedData.value = item;
                  openDetailModal();
                }
              },
              { default: () => item[`similarityRatio_${i}`] } // 按钮显示名称
            );
          }
        }
      ]
    });
  }

  columns = [...defaultColumns, ...contentsColumns];

  const allMapKeys: string[] = ['total'];
  const mapData: any = props.compareData.list[props.fileNumber].map[0].compareContent;
  for (const mapDataKey in mapData) {
    if (Object.hasOwn(mapData, mapDataKey)) {
      allMapKeys.push(mapDataKey);
    }
  }
  console.log('allMapKeys: ', allMapKeys);

  const indexList: number[] = [];
  const allMapDataList: any[] = [];
  let totalDataObj: any = {
    title: '总相似量',
    index: 0
  };
  for (let i: number = 0; i < props.compareData.list[props.fileNumber].map.length; i++) {
    const mapDataObj: any = props.compareData.list[props.fileNumber].map[i];
    const mapDataItem: any = mapDataObj.compareContent;
    console.log('mapDataObj: ', mapDataObj);

    // 总相似量数据
    let similarityRatio: number = 0;
    if (mapDataObj.totalErrorRate) {
      const similarityRatioNum: number = mapDataObj.totalErrorRate ? Number.parseFloat(mapDataObj.totalErrorRate) : 0;
      similarityRatio = Number.parseFloat((similarityRatioNum * 100).toFixed(2));
    }
    totalDataObj = {
      ...totalDataObj,
      indexNum: i,
      [`anomaliesNum_${i}`]: mapDataObj.compareErrorNumber,
      [`similarityRatio_${i}`]: `${similarityRatio}%`
    };

    indexList.push(i);
    const newMapDataList: any[] = [];
    for (const mapDataKey in mapDataItem) {
      if (Object.hasOwn(mapDataItem, mapDataKey)) {
        if (allMapKeys.includes(mapDataKey)) {
          const mapDataObj: any = {
            indexNum: i,
            [`${mapDataKey}`]: mapDataItem[mapDataKey]
          };
          newMapDataList.push(mapDataObj);
        }
      }
    }
    allMapDataList.push(newMapDataList);
  }

  console.log('totalDataObj', totalDataObj);
  console.log('allMapDataList: ', allMapDataList);

  const mapDataArr: any[] = [];
  for (let i: number = 0; i < allMapDataList.length / indexList.length; i++) {
    const mapDataObj: any = {
      indexNum: i,
      title: ''
    };

    for (let j: number = 0; j < indexList.length; j++) {
      const indexItem: number = indexList[j];
      mapDataObj[`anomaliesNum_${indexItem}`] = '';
      mapDataObj[`similarityRatio_${indexItem}`] = '';
    }
    mapDataArr.push(mapDataObj);
  }

  for (let i: number = 0; i < allMapDataList.length; i++) {
    const allMapDataItem: any = allMapDataList[i];
    // debugger;
    for (let j: number = 0; j < allMapDataItem.length; j++) {
      const allMapDataItemItem: any = allMapDataItem[j];
      // console.log('allMapDataItemItem: ', allMapDataItemItem)
      for (const allItemKey in allMapDataItemItem) {
        // console.log('allMapDataItemItemKey: ', allMapDataItemItemKey)
        if (Object.hasOwn(allMapDataItemItem, allItemKey)) {
          if (allItemKey !== 'indexNum') {
            for (let k: number = 0; k < titleMap.length; k++) {
              if (allItemKey === titleMap[k].key) {
                // console.log('titleStr1: ', i, j, titleStr);

                let similarityRatio: number = 0;
                if (allMapDataItemItem[allItemKey].length > 0) {
                  const similarityRatioNum: number = allMapDataItemItem[allItemKey][0].plagiarismRate
                    ? Number.parseFloat(allMapDataItemItem[allItemKey][0].plagiarismRate)
                    : 0;
                  similarityRatio = Number.parseFloat((similarityRatioNum * 100).toFixed(2));
                }

                const newData: any = {
                  ...mapDataArr[j],
                  title: titleMap[k].title,
                  compareKey: allItemKey,
                  index: titleMap[k].index,
                  [`anomaliesNum_${i}`]: allMapDataItemItem[allItemKey].length,
                  [`similarityRatio_${i}`]: `${similarityRatio}%`
                };
                // console.log('newData: ', newData);
                mapDataArr.splice(j, 1, newData);
              }
            }
          }
        }
      }
    }
  }

  // 添加总相似量到数据列表中
  mapDataArr.push(totalDataObj);

  // 排序
  mapDataArr.sort((a: any, b: any) => {
    return a.index - b.index;
  });

  tableData = mapDataArr;

  console.log('mapDataArr: ', mapDataArr);
}
</script>

<template>
  <div class="overview-box flex flex-col">
    <div class="flex flex-row items-center">
      <div class="title-tag"></div>
      <span class="title-text">基准文件：{{ compareData.list[fileNumber].bidUnit }}</span>
    </div>
    <NDataTable :columns="columns" :data="tableData" :max-height="500" :single-line="false" />
    <div class="flex flex-row items-center justify-end">
      <span class="warning-tips">
        *郑重申明：本平台检测结果只作为查重工具使用，不可作为他用，本平台和主体不承担使用检测结果作为他用的任何法律责任。
      </span>
    </div>
    <ExceptionDetail
      v-model:show="showDetailModal"
      :check-content="checkContent"
      :selected-index="selectedIndex"
      :selected-data="selectedData"
      :compare-data="compareData.list[fileNumber]"
    />
  </div>
</template>

<style scoped lang="scss">
.overview-box {
  padding: 25px 25px 0;
}
.title-tag {
  width: 6px;
  height: 20px;
  background: #806cfe;
}
.title-text {
  margin-left: 6px;
  font-weight: 500;
  font-size: 22px;
  color: #333333;
  line-height: 48px;
}
.warning-tips {
  margin: 15px 0;
  font-weight: 400;
  font-size: 16px;
  color: #ff7575;
  line-height: 48px;
}
:deep(.n-data-table .n-data-table-th) {
  //background-color: #f2f0ff;
  height: 54px;
  color: #666666;
  font-size: 18px;
}
</style>
